package com.bpmn.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.bpmn.common.exception.ServiceException;
import com.bpmn.system.domain.SysTenant;
import com.bpmn.system.domain.form.LoginForm;
import com.bpmn.system.domain.vo.LoginVo;
import com.bpmn.system.domain.vo.UserInfo;
import com.bpmn.system.mapper.SysTenantMapper;
import com.bpmn.system.service.AuthService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author rain
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private SysTenantMapper tenantMapper;

    @Override
    public LoginVo login(LoginForm form) {
        // 验证租户
        SysTenant tenant = tenantMapper.selectById(form.getTenantId());
        if (tenant == null || tenant.getStatus() == 0) {
            throw new ServiceException("租户不存在或已禁用");
        }
        // 验证用户
        if (!StrUtil.equals(form.getUsername(), tenant.getAdminUsername())) {
            throw new ServiceException("用户不存在或已禁用");
        }
        // 验证密码
        if (!BCrypt.checkpw(form.getPassword(), tenant.getAdminPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        // 生成token
        StpUtil.login(tenant.getId(), SaLoginConfig.setExtra("username", tenant.getAdminUsername()));
        String token = StpUtil.getTokenValue();
        // 返回登录信息
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(tenant.getAdminUsername());
        loginVo.setUser(userInfo);
        return loginVo;
    }

    @Override
    public UserInfo getUserInfo() {
        String tenantId = StpUtil.getLoginIdAsString();
        SysTenant sysTenant = tenantMapper.selectById(tenantId);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(sysTenant.getAdminUsername());
        return userInfo;
    }
} 